import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:self32/widget/model/auth_model.dart';
import 'package:self32/widget/model/person_model.dart';
import '../entity/reader_entity.dart';
import '../event/user_id_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/socket_manager.dart';
import '../util/camera_util.dart';
import '../util/timer_manager.dart';
import '../util/toast_util.dart';
import '../widget/app_bar.dart';
import '../widget/clipper.dart';
import '../widget/custom_floating_action_button_location.dart';
import '../widget/float_button.dart';
import '../widget/model/list_model.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'dart:ui' as ui;


class Mine extends StatefulWidget {
  const Mine({Key? key}) : super(key: key);

  @override
  State<Mine> createState() => _MineState();
}

class _MineState extends State<Mine> {

  SocketManager manager = SocketManager();

  var step = 1;

  StreamSubscription? userSubscription;

  RxBool preview = RxBool(false);
  CameraUtil camera = CameraUtil();
  // RxInt cameraId = RxInt(-1);
  // Timer? _timer;

  @override
  initState() {
    super.initState();

    userSubscription = eventFactory.on<UserIdEvent>().listen((event) {
      // currentTask.uid = event.uid;
      _getUser(event.uid);
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.back();
      });
    });
  }

  _getUser(uid) async {
    manager.setMode(Mode.none);
    ReaderEntity? reader = await findReader(uid);
    if(reader != null && reader.no != null && reader.no!.isNotEmpty){
      currentTask.uid = reader.no;
      currentTask.uName = reader.name;
      currentTask.readerEntity = reader;
      setState(() {
        step = 2;
      });
    }else{
      toastWarn('身份未认证');
      currentTask.clear();
    }
  }


  _title(){
    return Container(
        margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                currentTask.clear();
                timer.cancel();
                manager.setMode(Mode.none);
                Get.back();
              },
              child: Image.asset("assets/images/back.png", width: 40.w, fit: BoxFit.fitWidth,),
            ),
            Text("个人中心",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
            Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
          ],
        )
    );
  }

  final GlobalKey _globalKey = GlobalKey();

  _cameraWidget(){
    return Obx(() => Stack(
      alignment: AlignmentDirectional.center,
      children: [
        if(camera.cameraId.value > 0)...[
          RepaintBoundary(
            key: _globalKey,
            child:  ClipOval(
              clipper: ClipperOvalPath(),
              child: Transform.scale(
                scale:settingEntity.scale2??1,
                child: Transform.translate(offset: Offset((settingEntity.translateX2??0).w,(settingEntity.translateY2??0).h),
                  child: RotatedBox(
                    quarterTurns: settingEntity.rotate??0,
                    child: AspectRatio(
                        aspectRatio: camera.getPreviewSize(),
                        child: CameraPlatform.instance.buildPreview(camera.cameraId.value)
                    ),
                  ),
                ),
              ),),
          )
        ],
        Positioned(top:300.h,child: InkWell(
          child: Image.asset("assets/images/${preview.value?'result_confirm.jpg':'camera_cancel.png'}", width: 80.w, fit: BoxFit.fitWidth,),
          onTap: (){
            camera.stop();
            setState(() {
              step = 2;
            });
          },
        )),

        if(preview.value)...[
          Positioned(top:340.h,child:  InkWell(
            child:  Text('照片不满意？重拍',style: TextStyle(fontSize: 10.sp, decoration: TextDecoration.underline, color:const Color.fromRGBO(255, 26, 26, 1)),),
            onTap: () async {
              preview.value = false;
              await CameraPlatform.instance.resumePreview(camera.cameraId.value);
              camera.start((){
                _widgetToImage();
              });
            },
          ))

        ]
      ],
    ));
  }

  @override
  void dispose() {
    userSubscription?.cancel();
    userSubscription = null;
    camera.stop();
    // _timer?.cancel();
    // _timer = null;
    super.dispose();
  }

  _openCamera() async {
    if(camera.cameraId.value == -1){
      camera.cameraId.value = await camera.openCamera();
    }

    if(camera.cameraId.value != -1){
      camera.start((){
        _widgetToImage();
      });
      if(preview.value){
        preview.value = false;
        await CameraPlatform.instance.resumePreview(camera.cameraId.value);
      }
    }
  }


  _widgetToImage() {
    if(_globalKey.currentContext == null){
      // camera.disposeCurrentCamera();
      camera.stop();
      return;
    }
    RenderRepaintBoundary render = _globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    render.toImage().then((image){
      image.toByteData(format: ui.ImageByteFormat.png).then((byteData){
        if(byteData != null){
          String base64 = base64Encode(byteData.buffer.asUint8List());
          String base64Image = "data:image/png;base64,$base64";
          faceAdd(currentTask.uid,currentTask.uName,base64Image).then((data){
            if(data.$1 ){
              toastWarn('认证成功');
              tts.speak("认证成功");
              camera.stop();
              CameraPlatform.instance.pausePreview(camera.cameraId.value).then((value){
                preview.value = true;
              });

            }else{
              toastWarn('${data.$2}');
            }
          });
        }
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton:floatButton(),
        floatingActionButtonLocation:CustomFloatingActionButtonLocation(
            FloatingActionButtonLocation.endFloat, 0,-60.h),
        body: Stack(
            children: [
              Container(
                  width: double.infinity,
                  height: double.infinity,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage(
                        "assets/images/bg.png",
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      appBar(),
                      _title(),
                      if(step == 1)...[
                        AuthModel().show()
                      ],
                      if(step == 2)...[
                        PersonModel().show(showFaceAuth: settingEntity.face == 'nt'?false:true,callback: (){
                          if(step == 2){
                            setState(() {
                              step = 3;
                            });
                            _openCamera();
                          }
                        }),
                        ListModel().show(currentTask.readerEntity!.currentBorrowList),
                      ],
                      if(step == 3)...[
                        PersonModel().show(showFaceAuth: true),
                        SizedBox(height:20.h),
                        Text('请注视屏幕下方摄像头',style: TextStyle(fontSize: 10.sp, color: Colors.white,)),
                        SizedBox(height:60.h),
                        _cameraWidget()
                      ],
                    ],
                  )
              ),

            ]
        )
    );
  }
}